
import styled from 'styled-components';
import React, { CSSProperties, useEffect, useState } from 'react';
import { EllipsisOutlined, LoadingOutlined } from '@ant-design/icons';
import { Button, Avatar, Pagination, Card, Drawer, Breadcrumb } from 'antd';
import { useNavigate } from 'react-router-dom';
import { LeftOutlined, DeleteOutlined, CloudUploadOutlined, PlusOutlined, SettingOutlined, EditOutlined, LineChartOutlined, NodeIndexOutlined, ApartmentOutlined, PartitionOutlined, ProfileOutlined } from '@ant-design/icons';

import { Application, ApplicationCategory, appstoreGetCategories, appstoreGetMyApplication, installApplication, qiniuGetUrl } from '../../../services';
import { IconsHeader } from '../../../components';
import { ApplicationUploadVersion } from './application-upload-version';

import { MyApplicationDetail } from './my-application-detail';
import { ApplicationUploader } from './application-uploader';

export interface MyApplicationGridItemProps {
    style?: CSSProperties;
    item: Application;
    onDoubleClick?: (item: Application) => Promise<void>;
    onClick?: (item: Application, action?: string) => Promise<void>;
}

const MyApplicationGridItem: React.FC<MyApplicationGridItemProps> = (props: any) => {

    const [url, setUrl] = useState<string | null>(null);

    useEffect(() => {
        //
        qiniuGetUrl([props.item.icon]).then((url) => {
            console.log(url);
            if (url && url.length > 0) {
                setUrl(url[0]);
            }
        });
    }, [props.item.icon]);

    return (
        <Card
            bordered
            style={props.style}
            actions={[
                <CloudUploadOutlined key="setting" onClick={async () => {
                    props.onClick && props.onClick(props.item, 'UPLOAD_VERSION');
                }} />,
                <EditOutlined key="edit" onClick={async () => {
                    props.onClick && props.onClick(props.item, 'DETAIL');
                }} />,
                <LineChartOutlined key="ellipsis" onClick={async () => {
                    props.onClick && props.onClick(props.item, 'DATA');
                }} />,
            ]}
        >
            <Card.Meta
                avatar={!url ? <IconContainer><LoadingOutlined /></IconContainer> : <Icon src={url} />}
                title={props.item.name}
                description={<ApplicationDescription>{props.item.description}</ApplicationDescription>}
            />
        </Card>
    );
}

export const MyApplicationsPage = (props: any) => {

    const [categories, setCategories] = useState<Array<ApplicationCategory>>([]);

    const [detailOpen, setDetailOpen] = useState<boolean>(false);

    const [dataOpen, setDataOpen] = useState<boolean>(false);

    const [uploadOpen, setUploadOpen] = useState<boolean>(false);

    const [uploadVersionOpen, setUploadVersionOpen] = useState<boolean>(false);

    const [selected, setSelected] = useState<Application | null>(null);

    const [applications, setApplications] = useState<Array<Application>>([]);

    const [loading, setLoading] = useState<boolean>(false);

    const [action, setAction] = useState<string>('');

    const [pageSize, setPageSize] = useState<number>(20);

    const [page, setPage] = useState<number>(1);

    const [total, setTotal] = useState<number>(0);

    const navigate = useNavigate();

    const refresh = async (keywords: string, category: number, page: number, pageSize: number) => {
        setLoading(true);
        try {
            let res = await appstoreGetMyApplication(page, pageSize, { public_status: 1 });
            console.log(res);
            setApplications(res.data);
        } catch (error) {
            console.error(error);
        }
        setLoading(false);
    };


    useEffect(() => {
        // appstoreGetCategories
        appstoreGetCategories().then((data) => {
            setCategories(data);
        });
    }, []);

    useEffect(() => {
        //
        refresh('', 1, page, pageSize);
    }, [page, pageSize]);

    return (
        <Container style={props.style}>
            <Header>
                <IconsHeader
                    style={{
                        borderBottom: '1px solid #DEDEDE'
                    }}
                    activeKey={action}
                    itemSize={30}
                    leftItems={[
                        {
                            key: '返回',
                            label: '返回',
                            icon: <LeftOutlined />,
                            isAction: true,
                        },
                        {
                            key: '添加',
                            label: '添加',
                            icon: <PlusOutlined />,
                            isAction: true,
                        }
                    ]}
                    rightItems={[
                    ]}
                    onChange={async (key: string, isAction?: boolean) => {
                        if (isAction) {
                            //删除
                            if (key === '返回') {
                                //返回
                                navigate('/apps/appstore');
                            } else if (key === '添加') {
                                //返回
                                setUploadOpen(true);
                            }
                        } else {
                            setAction(key);
                        }
                    }}></IconsHeader>
                <Breadcrumb
                    style={{
                        padding: '0px 10px',
                        backgroundColor: '#DEDEDE',
                        height: '30px'
                    }}
                    items={[
                        {
                            title: <div style={{ cursor: 'pointer' }} onClick={() => {
                                navigate('/apps/appstore');
                            }}>应用商店</div>,
                        },
                        {
                            title: '我的应用',
                        },
                    ]}
                />
            </Header>
            <Content>
                <Grid>
                    {
                        applications && applications.map((item, index) => {
                            return (
                                <MyApplicationGridItem
                                    key={index}
                                    item={item}
                                    style={{
                                        width: '260px',
                                        height: '120px'
                                    }}
                                    onClick={async (item, action) => {
                                        setSelected(item);
                                        if (action === 'DETAIL') {
                                            setDetailOpen(true);
                                        } else if (action === 'UPLOAD_VERSION') {
                                            setUploadVersionOpen(true);
                                        } else if (action === 'DATA') {
                                            setDataOpen(true);
                                        }
                                    }}
                                    onDoubleClick={async (item) => {
                                    }}
                                ></MyApplicationGridItem>
                            );
                        })
                    }
                </Grid>
            </Content>
            <Footer>
                <Pagination
                    showSizeChanger={true}
                    defaultCurrent={page}
                    current={page}
                    pageSize={pageSize}
                    total={total}
                    onChange={(page, pageSize) => {
                        setPage(page);
                    }}
                    onShowSizeChange={(current, size) => {
                        setPageSize(size);
                    }}
                ></Pagination>
            </Footer>
            <Drawer
                title="数据统计"
                onClose={() => {
                    setDataOpen(false);
                }}
                width={'calc(100% - 220px)'}
                destroyOnClose={true}
                open={dataOpen}>
            </Drawer>
            <Drawer
                title="应用详情"
                onClose={() => {

                    setDetailOpen(false);
                }}
                width={'calc(100% - 220px)'}
                destroyOnClose={true}
                open={detailOpen}>
                <MyApplicationDetail categories={categories} item={selected}></MyApplicationDetail>
            </Drawer>
            <Drawer
                title="添加应用"
                onClose={() => {
                    setUploadOpen(false);
                }}
                width={'calc(100% - 220px)'}
                destroyOnClose={true}
                open={uploadOpen}>
                <ApplicationUploader categories={categories} onFinish={async () => {
                    //刷新列表
                }}></ApplicationUploader>
            </Drawer>
            <Drawer
                title="上传版本"
                onClose={() => {
                    setUploadVersionOpen(false);
                }}
                width={'calc(100% - 220px)'}
                destroyOnClose={true}
                open={uploadVersionOpen}>
                <ApplicationUploadVersion item={selected}></ApplicationUploadVersion>
            </Drawer>
        </Container>
    );
}


const EmptyContainer = styled.div`
    height: 100%;
    width: 100%;
    padding: 10px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
`;

const Container = styled.div`
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
    padding-top: 10px;
    background-color: #FFFFFF;
`;

const Header = styled.div`
    height: 48px;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
`;

const Content = styled.div`
    flex:1;
    width: 100%;
    overflow: auto;
    padding: 10px;
    background-color: #DEDEDE;
`;
const Footer = styled.div`
    height: 48px;
    width: 100%;
    padding: 10px;
    background-color: #FFFFFF;
`;

const Grid = styled.div`
    width: 100%;
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
`;

const IconContainer = styled.div`
    border-radius: 6px;
    width: 60px;
    height:60px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 30px;
    color: #ff7875;
`;

const Icon = styled.img`
    border-radius: 6px;
    width: 60px;
    height:60px;
`;

const ApplicationDescription = styled.div`
    text-overflow: -o-ellipsis-lastline;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    line-clamp: 1;
    -webkit-box-orient: vertical; 
`;
